<script setup lang="ts">
import { ref, computed, onUnmounted, onMounted } from 'vue'
import FolderModal from './FolderModal.vue'
import LoginModal from './LoginModal.vue'
import ChangePasswordModal from './ChangePasswordModal.vue'
import { authState, isLoggedIn, login, register, logout } from '../services/auth'
import { OfflineManager } from '../services/crudApi'
import { showError, showSuccess, showInfo } from '../services/notification'
import { formatFullDateTime } from '../utils/dateUtils'

/**
 * 文件夹列表组件
 * 负责显示和管理文件夹
 */

interface Folder {
  id: number
  name: string
  count: number
  isDefault?: boolean
  isShared?: boolean
  parentId?: number | null
  children?: Folder[]
  isExpanded?: boolean
  shareLink?: string
  sharePassword?: string
  syncStatus?: 'local' | 'synced' | 'syncing' | 'error'
  serverId?: string
  createdAt?: string
  updatedAt?: string
}

const props = defineProps<{
  folders: Folder[]
  currentFolder: string
}>()

const emit = defineEmits<{
  folderSelect: [folder: Folder]
  createFolder: [name: string, parentId?: number | null, isShared?: boolean]
  renameFolder: [id: number, name: string]
  deleteFolder: [id: number]
  updateFolder: [folder: Folder]
  moveFolder: [folderId: number, targetFolderId: number]
  reorderFolders: [draggedFolderId: number, targetFolderId: number, position: 'before' | 'after']
  moveNoteToFolder: [noteId: number, targetFolderId: number]
  convertFolderToShared: [folderId: number]
  convertFolderToPrivate: [folderId: number]
  convertNoteToShared: [noteId: number]
  convertNoteToPrivate: [noteId: number]
  createSharedNote: [noteData: any, folderId: number]
  showImageManager: []
  showSettings: []
}>()

// 文件夹管理状态
const expandedFolders = ref<Set<number>>(new Set())

// 拖动调整高度相关状态
const isDragging = ref(false)
const sharedFoldersHeight = ref(200) // 共享文件夹区域的初始高度
const minHeight = 100 // 最小高度
const maxHeight = 400 // 最大高度

// 文件夹拖拽相关状态
const draggedFolderId = ref<number | null>(null)
const dragOverFolderId = ref<number | string | null>(null)
const draggedFolder = ref<Folder | null>(null)

// 弹窗状态
const showModal = ref(false)
const modalTitle = ref('')
const modalInitialValue = ref('')
const currentEditingFolderId = ref<number | null>(null)
const isCreatingFolder = ref(false)
const isCreatingSharedFolder = ref(false)

// 登录状态
const showLoginModal = ref(false)
const showChangePasswordModal = ref(false)
const loginError = ref('')
const loginSuccess = ref('')

// 右键菜单状态
const showContextMenu = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)
const contextMenuFolder = ref<Folder | null>(null)

// 共享链接状态
const showShareLinkModal = ref(false)
const shareLink = ref('')
const sharePassword = ref('')
const isGeneratingShareLink = ref(false)

// 共享文件夹相关状态
const showAddSharedModal = ref(false)
const sharedLinkInput = ref('')
const isLoadingSharedFolder = ref(false)
const sharedFolderError = ref('')

// 文件夹颜色选项
const folderColors = ref([
  { name: '蓝色', value: '#007bff' },
  { name: '绿色', value: '#28a745' },
  { name: '红色', value: '#dc3545' },
  { name: '橙色', value: '#fd7e14' },
  { name: '紫色', value: '#6f42c1' },
  { name: '青色', value: '#17a2b8' },
  { name: '粉色', value: '#e83e8c' },
  { name: '黄色', value: '#ffc107' }
])

// 同步状态管理
const syncStatus = ref({
  hasPendingData: false,
  pendingCount: 0,
  folders: 0,
  notes: 0,
  isRetrying: false
})

/**
 * 获取文件夹层级深度
 * @param folder 文件夹对象
 * @returns 层级深度
 */
const getFolderDepth = (folder: Folder): number => {
  let depth = 0
  let currentFolder = folder
  while (currentFolder.parentId) {
    depth++
    const parent = props.folders.find((f) => f.id === currentFolder.parentId)
    if (!parent) break
    currentFolder = parent
  }
  return depth
}

/**
 * 检查文件夹是否有子文件夹
 * @param folderId 文件夹ID
 * @returns 是否有子文件夹
 */
const hasChildren = (folderId: number): boolean => {
  return props.folders.some(folder => folder.parentId === folderId)
}

/**
 * 切换文件夹展开/收起状态
 * @param folderId 文件夹ID
 */
const toggleFolderExpansion = (folderId: number): void => {
  if (expandedFolders.value.has(folderId)) {
    expandedFolders.value.delete(folderId)
  } else {
    expandedFolders.value.add(folderId)
  }
}

/**
 * 检查文件夹是否展开
 * @param folderId 文件夹ID
 * @returns 是否展开
 */
const isFolderExpanded = (folderId: number): boolean => {
  return expandedFolders.value.has(folderId)
}

/**
 * 检查文件夹是否应该显示（考虑父文件夹的展开状态）
 * @param folder 文件夹对象
 * @returns 是否应该显示
 */
const shouldShowFolder = (folder: Folder): boolean => {
  if (!folder.parentId) {
    return true // 根级文件夹总是显示
  }
  
  // 检查所有父级文件夹是否都展开
  let currentParentId = folder.parentId
  while (currentParentId) {
    if (!expandedFolders.value.has(currentParentId)) {
      return false
    }
    const parent = props.folders.find(f => f.id === currentParentId)
    currentParentId = parent?.parentId || null
  }
  
  return true
}

/**
 * 获取排序后的文件夹列表（按层级排序，考虑展开状态）
 */
const sortedFolders = computed(() => {
  const buildTree = (parentId: number | null = null): Folder[] => {
    return props.folders
      .filter((folder) => folder.parentId === parentId)
      .sort((a, b) => {
        // 默认文件夹排在前面
        if (a.isDefault && !b.isDefault) return -1
        if (!a.isDefault && b.isDefault) return 1
        
        // 非默认文件夹按sortOrder排序，如果没有sortOrder则按名称排序
        if (!a.isDefault && !b.isDefault) {
          const aOrder = a.sortOrder || 0
          const bOrder = b.sortOrder || 0
          if (aOrder !== bOrder) {
            return aOrder - bOrder
          }
        }
        
        return a.name.localeCompare(b.name)
      })
      .reduce((acc: Folder[], folder) => {
        acc.push(folder)
        // 只有当文件夹展开时才显示子文件夹
        if (expandedFolders.value.has(folder.id)) {
          acc.push(...buildTree(folder.id))
        }
        return acc
      }, [])
  }
  return buildTree()
})

/**
 * 获取可见的文件夹列表（过滤掉被折叠的文件夹）
 */
const visibleFolders = computed(() => {
  return sortedFolders.value.filter(folder => shouldShowFolder(folder))
})

/**
 * 选择文件夹
 * @param folder 文件夹对象
 */
const selectFolder = (folder: Folder): void => {
  emit('folderSelect', folder)
}

/**
 * 处理文件夹点击事件
 * @param folder 文件夹对象
 */
const handleFolderClick = (folder: Folder): void => {
  // 如果文件夹有子文件夹，先切换展开状态
  if (hasChildren(folder.id)) {
    toggleFolderExpansion(folder.id)
  }
  // 然后选择文件夹
  selectFolder(folder)
}

/**
 * 显示新建文件夹弹窗
 */
const showCreateFolder = (): void => {
  modalTitle.value = '新建文件夹'
  modalInitialValue.value = ''
  currentEditingFolderId.value = null
  isCreatingFolder.value = true
  isCreatingSharedFolder.value = false
  showModal.value = true
}

/**
 * 显示重命名文件夹弹窗
 * @param folder 要重命名的文件夹
 */
const startRenameFolder = (folder: Folder): void => {
  modalTitle.value = '重命名文件夹'
  modalInitialValue.value = folder.name
  currentEditingFolderId.value = folder.id
  isCreatingFolder.value = false
  showModal.value = true
}

/**
 * 处理弹窗确认
 * @param value 输入的文件夹名称
 */
const handleModalConfirm = (value: string): void => {
  if (isCreatingFolder.value) {
    if (isCreatingSharedFolder.value) {
      emit('createFolder', value, null, true) // 第三个参数表示是共享文件夹
    } else {
      emit('createFolder', value, null, false)
    }
  } else if (currentEditingFolderId.value) {
    emit('renameFolder', currentEditingFolderId.value, value)
  }
}

/**
 * 处理弹窗关闭
 */
const handleModalClose = (): void => {
  showModal.value = false
  modalTitle.value = ''
  modalInitialValue.value = ''
  currentEditingFolderId.value = null
  isCreatingFolder.value = false
  isCreatingSharedFolder.value = false
}

/**
 * 删除文件夹
 * @param folder 要删除的文件夹
 */
const deleteFolder = (folder: Folder): void => {
  if (confirm(`确定要删除文件夹 "${folder.name}" 吗？`)) {
    emit('deleteFolder', folder.id)
  }
}



/**
 * 显示登录弹窗
 */
const showLogin = (): void => {
  showLoginModal.value = true
}

/**
 * 处理显示登录框事件
 */
const handleShowLogin = (event: CustomEvent): void => {
  console.log('收到显示登录框事件:', event.detail)
  showLogin()
}

// 监听显示登录框事件
window.addEventListener('show:login', handleShowLogin as EventListener)

// 组件挂载时更新同步状态
onMounted(() => {
  updateSyncStatus()
  // 定期更新同步状态
  const syncStatusInterval = setInterval(updateSyncStatus, 5000)
  
  onUnmounted(() => {
    clearInterval(syncStatusInterval)
  })
})

onUnmounted(() => {
  window.removeEventListener('show:login', handleShowLogin as EventListener)
})

/**
 * 处理登录
 * @param email 邮箱
 * @param password 密码
 * @param serverUrl 服务器地址
 */
const handleLogin = async (email: string, password: string, serverUrl: string): Promise<void> => {
  try {
    loginError.value = ''
    loginSuccess.value = ''
    
    const result = await login(email, password, serverUrl)
    
    if (result.success) {
      loginSuccess.value = '登录成功！'
      showLoginModal.value = false
      console.log('登录成功:', email)
      
      // 登录成功后自动执行数据获取和同步
      await handlePostLoginActions()
    } else {
      loginError.value = result.message || '登录失败'
    }
  } catch (error) {
    console.error('登录过程中发生错误:', error)
    loginError.value = '登录过程中发生错误'
  }
}

/**
 * 处理注册
 * @param email 邮箱
 * @param password 密码
 * @param serverUrl 服务器地址
 */
const handleRegister = async (email: string, password: string, serverUrl: string): Promise<void> => {
  try {
    loginError.value = ''
    loginSuccess.value = ''
    
    const result = await register(email, password, serverUrl)
    
    if (result.success) {
      loginSuccess.value = result.message || '注册成功！请登录'
      console.log('注册成功:', email)
    } else {
      loginError.value = result.message || '注册失败'
    }
  } catch (error) {
    console.error('注册过程中发生错误:', error)
    loginError.value = '注册过程中发生错误'
  }
}

/**
 * 处理登出
 */
const handleLogout = async (): Promise<void> => {
  if (confirm('确定要登出吗？')) {
    try {
      await logout()
      console.log('已登出')
    } catch (error) {
      console.error('登出过程中发生错误:', error)
    }
  }
}

/**
 * 关闭登录弹窗
 */
const closeLoginModal = (): void => {
  showLoginModal.value = false
  loginError.value = ''
  loginSuccess.value = ''
}

/**
 * 更新同步状态
 */
const updateSyncStatus = (): void => {
  if (isLoggedIn.value) {
    const status = OfflineManager.getSyncStatus()
    syncStatus.value = {
      ...status,
      isRetrying: syncStatus.value.isRetrying
    }
  } else {
    syncStatus.value = {
      hasPendingData: false,
      pendingCount: 0,
      folders: 0,
      notes: 0,
      isRetrying: false
    }
  }
}

/**
 * 重试同步待同步数据
 */
const retrySyncPendingData = async (): Promise<void> => {
  if (!isLoggedIn.value || syncStatus.value.isRetrying) {
    return
  }
  
  try {
    syncStatus.value.isRetrying = true
    showInfo('正在重试同步待同步数据...', '数据同步')
    
    const result = await OfflineManager.retrySyncPendingData()
    
    if (result.success) {
      showSuccess(`成功同步 ${result.totalCount} 项数据`, '同步完成')
    } else {
      showInfo(`手动重试：${result.failedCount}/${result.totalCount} 项数据同步失败，将启动自动重试`, '同步失败')
      // 通知App组件启动自动重试
      window.dispatchEvent(new CustomEvent('sync:start-auto-retry', {
        detail: { reason: 'manual_retry_failed' }
      }))
    }
    
    // 更新同步状态
    updateSyncStatus()
    
  } catch (error) {
    console.error('重试同步失败:', error)
    showError('重试同步失败，请稍后再试', '同步错误')
  } finally {
    syncStatus.value.isRetrying = false
  }
}

/**
 * 处理登录后的操作
 */
const handlePostLoginActions = async (): Promise<void> => {
  try {
    showInfo('正在获取服务器数据...', '数据同步')
    
    // 1. 触发App组件重新加载服务器数据
    // 通过自定义事件通知App组件
    window.dispatchEvent(new CustomEvent('user:login', {
      detail: { message: '用户登录成功，开始数据同步' }
    }))
    
    // 2. 等待一下让数据加载完成
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 3. 更新同步状态
    updateSyncStatus()
    
    console.log('登录后数据获取和同步操作已启动')
    
  } catch (error) {
    console.error('登录后操作失败:', error)
    showError('登录后数据同步失败，请手动刷新页面', '同步错误')
  }
}

/**
 * 显示修改密码弹窗
 */
const showChangePassword = (): void => {
  showChangePasswordModal.value = true
}

/**
 * 关闭修改密码弹窗
 */
const closeChangePasswordModal = (): void => {
  showChangePasswordModal.value = false
}

/**
 * 修改密码成功回调
 */
const handlePasswordChangeSuccess = (): void => {
  console.log('密码修改成功')
}

// 同步相关函数已删除

/**
 * 显示右键菜单
 * @param folder 文件夹对象
 * @param event 鼠标事件
 */
const showFolderContextMenu = (folder: Folder, event: MouseEvent): void => {
  if (folder.isDefault) return // 默认文件夹不显示右键菜单

  event.preventDefault()
  contextMenuFolder.value = folder
  contextMenuX.value = event.clientX
  contextMenuY.value = event.clientY
  showContextMenu.value = true
}

/**
 * 隐藏右键菜单
 */
const hideContextMenu = (): void => {
  showContextMenu.value = false
  contextMenuFolder.value = null
}

/**
 * 右键菜单重命名
 */
const contextMenuRename = (): void => {
  if (contextMenuFolder.value) {
    startRenameFolder(contextMenuFolder.value)
  }
  hideContextMenu()
}

/**
 * 右键菜单删除
 */
const contextMenuDelete = (): void => {
  if (contextMenuFolder.value) {
    deleteFolder(contextMenuFolder.value)
  }
  hideContextMenu()
}

/**
 * 右键菜单设置为共享
 */
const contextMenuSetShared = (): void => {
  if (contextMenuFolder.value && !contextMenuFolder.value.isDefault && !contextMenuFolder.value.isShared) {
    setFolderShared(contextMenuFolder.value, true)
  }
  hideContextMenu()
}

/**
 * 检查文件夹是否可以上移
 * @param folder 文件夹对象
 * @returns 是否可以上移
 */
const canMoveUp = (folder: Folder): boolean => {
  const siblings = props.folders
    .filter(f => f.parentId === folder.parentId && !f.isDefault)
    .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
  
  const currentIndex = siblings.findIndex(f => f.id === folder.id)
  return currentIndex > 0
}

/**
 * 检查文件夹是否可以下移
 * @param folder 文件夹对象
 * @returns 是否可以下移
 */
const canMoveDown = (folder: Folder): boolean => {
  const siblings = props.folders
    .filter(f => f.parentId === folder.parentId && !f.isDefault)
    .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
  
  const currentIndex = siblings.findIndex(f => f.id === folder.id)
  return currentIndex >= 0 && currentIndex < siblings.length - 1
}

/**
 * 右键菜单上移文件夹
 */
const contextMenuMoveUp = (): void => {
  if (contextMenuFolder.value && canMoveUp(contextMenuFolder.value)) {
    const siblings = props.folders
      .filter(f => f.parentId === contextMenuFolder.value!.parentId && !f.isDefault)
      .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
    
    const currentIndex = siblings.findIndex(f => f.id === contextMenuFolder.value!.id)
    if (currentIndex > 0) {
      const targetFolder = siblings[currentIndex - 1]
      emit('reorderFolders', contextMenuFolder.value.id, targetFolder.id, 'before')
    }
  }
  hideContextMenu()
}

/**
 * 右键菜单下移文件夹
 */
const contextMenuMoveDown = (): void => {
  if (contextMenuFolder.value && canMoveDown(contextMenuFolder.value)) {
    const siblings = props.folders
      .filter(f => f.parentId === contextMenuFolder.value!.parentId && !f.isDefault)
      .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
    
    const currentIndex = siblings.findIndex(f => f.id === contextMenuFolder.value!.id)
    if (currentIndex >= 0 && currentIndex < siblings.length - 1) {
      const targetFolder = siblings[currentIndex + 1]
      emit('reorderFolders', contextMenuFolder.value.id, targetFolder.id, 'after')
    }
  }
  hideContextMenu()
}

/**
 * 右键菜单取消共享
 */
const contextMenuCancelShared = (): void => {
  if (contextMenuFolder.value && contextMenuFolder.value.isShared) {
    setFolderShared(contextMenuFolder.value, false)
  }
  hideContextMenu()
}

/**
 * 右键菜单获取共享链接
 */
const contextMenuGetShareLink = async (): Promise<void> => {
  if (contextMenuFolder.value && contextMenuFolder.value.isShared) {
    await generateShareLink(contextMenuFolder.value)
  }
  hideContextMenu()
}

/**
 * 生成共享链接
 * @param folder 文件夹对象
 */
const generateShareLink = async (folder: Folder): Promise<void> => {
  try {
    isGeneratingShareLink.value = true
    
    // 如果文件夹已有共享链接，直接显示
    if (folder.shareLink) {
      shareLink.value = folder.shareLink
      sharePassword.value = folder.sharePassword || ''
      showShareLinkModal.value = true
      return
    }
    
    // TODO: 调用共享服务生成链接
    // const shareInfo = await createShareLink('folder', folder.id, sharePassword.value)
    // if (shareInfo) {
    //   shareLink.value = shareInfo.shareLink
    //   showShareLinkModal.value = true
    //   // 更新文件夹的共享链接信息
    //   emit('updateFolderShareLink', folder.id, shareInfo.shareLink, shareInfo.password)
    // }
    
    // 临时模拟生成链接
    const mockShareId = `folder_${folder.id}_${Date.now()}`
    shareLink.value = `${window.location.origin}/share/${mockShareId}`
    sharePassword.value = ''
    showShareLinkModal.value = true
    
  } catch (error) {
    console.error('生成共享链接失败:', error)
    alert('生成共享链接失败，请稍后重试')
  } finally {
    isGeneratingShareLink.value = false
  }
}

/**
 * 复制共享链接到剪贴板
 */
const copyShareLink = async (): Promise<void> => {
  try {
    await navigator.clipboard.writeText(shareLink.value)
    alert('共享链接已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    alert('复制失败，请手动复制链接')
  }
}

/**
 * 关闭共享链接弹窗
 */
const closeShareLinkModal = (): void => {
  showShareLinkModal.value = false
  shareLink.value = ''
  sharePassword.value = ''
}

/**
 * 设置文件夹共享状态
 * @param folder 文件夹对象
 * @param isShared 是否共享
 */
const setFolderShared = (folder: Folder, isShared: boolean): void => {
  if (isShared) {
    // 设置为共享文件夹
    const updatedFolder = {
      ...folder,
      isShared: true
      // 不修改 parentId，保持原有层级关系
    }
    
    emit('updateFolder', updatedFolder)
    console.log(`文件夹 "${folder.name}" 已设置为共享`)
  } else {
    // 取消共享
    const updatedFolder = {
      ...folder,
      isShared: false,
      shareLink: undefined,
      sharePassword: undefined
    }
    
    emit('updateFolder', updatedFolder)
    console.log(`文件夹 "${folder.name}" 已取消共享`)
  }
}

/**
 * 获取扁平化的共享文件夹列表
 * @returns 扁平化的共享文件夹数组
 */
const getSharedFoldersFlat = (): Folder[] => {
  // 获取所有共享文件夹（包括有层级关系的），但在共享区域扁平显示
  return props.folders.filter(f => f.isShared && !f.isDefault)
}

/**
 * 截断文件夹名称
 * @param name 文件夹名称
 * @param maxLength 最大长度
 * @returns 截断后的名称
 */
const truncateFolderName = (name: string, maxLength: number = 15): string => {
  if (name.length <= maxLength) {
    return name
  }
  return name.substring(0, maxLength - 3) + '...'
}

/**
 * 显示创建共享文件夹弹窗
 */
const showCreateSharedFolder = (): void => {
  modalTitle.value = '新建共享文件夹'
  modalInitialValue.value = ''
  currentEditingFolderId.value = null
  isCreatingFolder.value = true
  isCreatingSharedFolder.value = true
  showModal.value = true
}

/**
 * 显示添加共享文件夹弹窗
 */
const showAddSharedFolderModal = (): void => {
  showAddSharedModal.value = true
  sharedLinkInput.value = ''
  sharedFolderError.value = ''
}

/**
 * 关闭添加共享文件夹弹窗
 */
const closeAddSharedModal = (): void => {
  showAddSharedModal.value = false
  sharedLinkInput.value = ''
  sharedFolderError.value = ''
  isLoadingSharedFolder.value = false
}

/**
 * 处理添加共享文件夹
 */
const handleAddSharedFolder = async (): Promise<void> => {
  if (!sharedLinkInput.value.trim()) {
    sharedFolderError.value = '请输入共享链接'
    return
  }
  
  isLoadingSharedFolder.value = true
  sharedFolderError.value = ''
  
  try {
    // 解析共享链接，提取shareId
    const shareId = extractShareIdFromLink(sharedLinkInput.value)
    if (!shareId) {
      throw new Error('无效的共享链接格式')
    }
    
    // 调用API获取共享内容
    const response = await fetch(`${authState.serverUrl}/api/v1/shared/${shareId}/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({})
    })
    
    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.error || '获取共享内容失败')
    }
    
    const sharedData = await response.json()
    
    // 检查是否为文件夹类型
    if (sharedData.resourceType !== 'folder') {
      throw new Error('该链接不是共享文件夹')
    }
    
    // 创建本地文件夹副本
    const newFolder: Folder = {
      id: Date.now(), // 临时ID，实际应该由后端生成
      name: `${sharedData.title} (共享)`,
      count: sharedData.notes ? sharedData.notes.length : 0,
      isDefault: false,
      isShared: true,
      parentId: null,
      sortOrder: 999, // 放在最后
      createdAt: formatFullDateTime(),
      updatedAt: formatFullDateTime(),
      syncStatus: 'local'
    }
    
    // 发射事件通知父组件添加文件夹
    emit('createFolder', newFolder.name, null, true)
    
    // 等待一下让文件夹创建完成，然后添加笔记
    setTimeout(() => {
      if (sharedData.notes && sharedData.notes.length > 0) {
        for (const noteData of sharedData.notes) {
          const newNote = {
            title: noteData.title,
            content: noteData.content,
            createdAt: noteData.createdAt,
            updatedAt: noteData.updatedAt,
            syncStatus: 'local'
          }
          // 发射事件通知父组件添加共享笔记
          emit('createSharedNote', newNote, newFolder.id)
          console.log('添加共享笔记:', newNote.title)
        }
      }
    }, 100)
    
    closeAddSharedModal()
    console.log('共享文件夹添加成功:', newFolder.name)
  } catch (error) {
    sharedFolderError.value = error instanceof Error ? error.message : '获取共享文件夹失败，请检查链接是否正确'
    console.error('添加共享文件夹失败:', error)
  } finally {
    isLoadingSharedFolder.value = false
  }
}

/**
 * 从共享链接中提取shareId
 * @param link 共享链接
 * @returns shareId或null
 */
const extractShareIdFromLink = (link: string): string | null => {
  try {
    // 支持多种链接格式
    // 1. 完整URL: https://domain.com/shared/abc123
    // 2. 路径: /shared/abc123
    // 3. 直接ID: abc123
    
    const url = new URL(link.startsWith('http') ? link : `https://example.com${link.startsWith('/') ? link : '/shared/' + link}`)
    const pathParts = url.pathname.split('/')
    
    // 查找 'shared' 后面的部分
    const sharedIndex = pathParts.indexOf('shared')
    if (sharedIndex !== -1 && sharedIndex + 1 < pathParts.length) {
      return pathParts[sharedIndex + 1]
    }
    
    // 如果没有找到，尝试直接使用输入作为ID
    if (link.match(/^[a-zA-Z0-9]+$/)) {
      return link
    }
    
    return null
  } catch (error) {
    // 如果URL解析失败，尝试直接使用输入作为ID
    if (link.match(/^[a-zA-Z0-9]+$/)) {
      return link
    }
    return null
  }
}

/**
 * 开始拖动调整高度
 * @param event 鼠标事件
 */
const startDragging = (event: MouseEvent): void => {
  isDragging.value = true
  const startY = event.clientY
  const startHeight = sharedFoldersHeight.value
  
  const handleMouseMove = (e: MouseEvent): void => {
    if (!isDragging.value) return
    
    const deltaY = e.clientY - startY
    const newHeight = Math.max(minHeight, Math.min(maxHeight, startHeight + deltaY))
    sharedFoldersHeight.value = newHeight
  }
  
  const handleMouseUp = (): void => {
    isDragging.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    document.body.style.cursor = ''
    document.body.style.userSelect = ''
  }
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
  document.body.style.cursor = 'ns-resize'
  document.body.style.userSelect = 'none'
}

/**
 * 处理文件夹拖拽开始
 * @param folder 被拖拽的文件夹
 * @param event 拖拽事件
 */
const handleDragStart = (folder: Folder, event: DragEvent): void => {
  console.log('开始拖拽文件夹:', folder.name, 'ID:', folder.id)
  draggedFolderId.value = folder.id
  draggedFolder.value = folder
  
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('text/plain', folder.id.toString())
  }
}

/**
 * 处理文件夹拖拽结束
 * @param event 拖拽事件
 */
const handleDragEnd = (event: DragEvent): void => {
  draggedFolderId.value = null
  draggedFolder.value = null
  dragOverFolderId.value = null
}

/**
 * 处理文件夹拖拽悬停
 * @param folder 目标文件夹
 * @param event 拖拽事件
 */
const handleDragOver = (folder: Folder, event: DragEvent): void => {
  event.preventDefault()
  
  // 检查是否是文件夹拖拽
  if (draggedFolderId.value && draggedFolderId.value !== folder.id) {
    dragOverFolderId.value = folder.id
    
    if (event.dataTransfer) {
      event.dataTransfer.dropEffect = 'move'
    }
  }
  
  // 检查是否是笔记拖拽
  const draggedData = event.dataTransfer?.getData('text/plain')
  if (draggedData && !draggedFolderId.value) {
    // 这是笔记拖拽
    dragOverFolderId.value = folder.id
    
    if (event.dataTransfer) {
      event.dataTransfer.dropEffect = 'move'
    }
  }
}

/**
 * 处理文件夹拖拽离开
 * @param event 拖拽事件
 */
const handleDragLeave = (event: DragEvent): void => {
  // 只有当鼠标真正离开元素时才清除高亮
  const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
  const x = event.clientX
  const y = event.clientY
  
  if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
    dragOverFolderId.value = null
  }
}

/**
 * 处理文件夹拖拽放置
 * @param targetFolder 目标文件夹
 * @param event 拖拽事件
 */
const handleDrop = (targetFolder: Folder, event: DragEvent): void => {
  console.log('拖拽放置到文件夹:', targetFolder.name, 'ID:', targetFolder.id)
  console.log('当前拖拽的文件夹:', draggedFolder.value?.name, 'ID:', draggedFolder.value?.id)
  
  event.preventDefault()
  dragOverFolderId.value = null
  
  const draggedData = event.dataTransfer?.getData('text/plain')
  
  // 处理文件夹拖拽
  if (draggedFolder.value && draggedFolder.value.id !== targetFolder.id) {
    // 检查是否是默认文件夹
    if (draggedFolder.value.isDefault) {
      console.warn('默认文件夹不能被移动或排序')
      return
    }
    
    // 检查是否会造成循环引用
    if (isDescendantOf(targetFolder.id, draggedFolder.value.id)) {
      console.warn('不能将文件夹移动到其子文件夹中')
      return
    }
    
    // 获取鼠标在目标元素中的位置
    const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
    const mouseY = event.clientY
    const elementTop = rect.top
    const elementHeight = rect.height
    const relativeY = mouseY - elementTop
    
    // 如果拖拽到元素的上半部分或下半部分，进行排序
    // 如果拖拽到中间部分，移动到子文件夹
    const threshold = elementHeight * 0.3 // 30%的区域用于排序
    
    if (relativeY < threshold) {
      // 拖拽到上半部分，插入到目标文件夹之前
      if (draggedFolder.value.parentId === targetFolder.parentId) {
        emit('reorderFolders', draggedFolder.value.id, targetFolder.id, 'before')
        console.log(`将文件夹 ${draggedFolder.value.name} 移动到 ${targetFolder.name} 之前`)
      } else {
        // 不同父级，移动到目标文件夹的父级
        emit('moveFolder', draggedFolder.value.id, targetFolder.parentId || 0)
        console.log(`移动文件夹 ${draggedFolder.value.name} 到 ${targetFolder.name} 的同级`)
      }
    } else if (relativeY > elementHeight - threshold) {
      // 拖拽到下半部分，插入到目标文件夹之后
      if (draggedFolder.value.parentId === targetFolder.parentId) {
        emit('reorderFolders', draggedFolder.value.id, targetFolder.id, 'after')
        console.log(`将文件夹 ${draggedFolder.value.name} 移动到 ${targetFolder.name} 之后`)
      } else {
        // 不同父级，移动到目标文件夹的父级
        emit('moveFolder', draggedFolder.value.id, targetFolder.parentId || 0)
        console.log(`移动文件夹 ${draggedFolder.value.name} 到 ${targetFolder.name} 的同级`)
      }
    } else {
      // 拖拽到中间部分，移动到目标文件夹内部
      emit('moveFolder', draggedFolder.value.id, targetFolder.id)
      console.log(`移动文件夹 ${draggedFolder.value.name} 到 ${targetFolder.name} 内部`)
    }
    return
  }
  
  // 处理笔记拖拽
  if (draggedData && !draggedFolder.value) {
    const noteId = parseInt(draggedData)
    if (!isNaN(noteId)) {
      // 检查目标文件夹类型
      if (targetFolder.name === '未分类笔记') {
        // 移动到未分类笔记
        emit('moveNoteToFolder', noteId, null)
        console.log(`移动笔记到未分类笔记`)
      } else if (!targetFolder.isDefault) {
        // 移动到普通文件夹
        emit('moveNoteToFolder', noteId, targetFolder.id)
        console.log(`移动笔记到文件夹 ${targetFolder.name}`)
      }
    }
  }
}

/**
 * 检查文件夹是否是另一个文件夹的后代
 * @param folderId 要检查的文件夹ID
 * @param ancestorId 祖先文件夹ID
 * @returns 是否是后代
 */
const isDescendantOf = (folderId: number, ancestorId: number): boolean => {
  const folder = props.folders.find(f => f.id === folderId)
  if (!folder || !folder.parentId) {
    return false
  }
  
  if (folder.parentId === ancestorId) {
    return true
  }
  
  return isDescendantOf(folder.parentId, ancestorId)
}

/**
 * 处理根目录拖拽悬停
 * @param event 拖拽事件
 */
const handleRootDragOver = (event: DragEvent): void => {
  event.preventDefault()
  
  if (draggedFolderId.value) {
    dragOverFolderId.value = 'root'
    
    if (event.dataTransfer) {
      event.dataTransfer.dropEffect = 'move'
    }
  }
}

/**
 * 处理根目录拖拽离开
 * @param event 拖拽事件
 */
const handleRootDragLeave = (event: DragEvent): void => {
  const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
  const x = event.clientX
  const y = event.clientY
  
  if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
    if (dragOverFolderId.value === 'root') {
      dragOverFolderId.value = null
    }
  }
}

/**
 * 处理根目录拖拽放置
 * @param event 拖拽事件
 */
const handleRootDrop = (event: DragEvent): void => {
  event.preventDefault()
  dragOverFolderId.value = null
  
  if (draggedFolder.value && draggedFolder.value.parentId !== null) {
    // 移动文件夹到根目录（parentId设为null）
    draggedFolder.value.parentId = null
    console.log(`移动文件夹 ${draggedFolder.value.name} 到根目录`)
    
    // 发射更新文件夹事件
    emit('updateFolder', draggedFolder.value)
  }
}

/**
 * 更改文件夹颜色
 * @param color 新的颜色值
 */
const changeFolderColor = (color: string): void => {
  if (contextMenuFolder.value) {
    // 更新文件夹颜色
    contextMenuFolder.value.iconColor = color
    
    // 发射更新文件夹事件
    emit('updateFolder', contextMenuFolder.value)
    
    console.log(`文件夹 ${contextMenuFolder.value.name} 颜色已更改为 ${color}`)
  }
  
  // 隐藏右键菜单
  hideContextMenu()
}
</script>

<template>
  <div class="folder-list-container" @click="hideContextMenu">
    <!-- 顶部用户区域 -->
    <div class="user-section">
      <div
        class="user-info"
        @click="!isLoggedIn && showLogin()"
        :class="{ clickable: !isLoggedIn }"
      >
        <div class="user-avatar">{{ isLoggedIn ? authState.user?.username.charAt(0).toUpperCase() : 'U' }}</div>
        <div class="user-details">
          <span class="user-name">{{ isLoggedIn ? authState.user?.username : '未登录' }}</span>
          <div v-if="isLoggedIn" class="sync-status">
            <div v-if="syncStatus.hasPendingData" class="pending-sync-indicator">
              <svg viewBox="0 0 24 24" width="12" height="12" class="sync-icon">
                <path fill="currentColor" d="M12,18A6,6 0 0,1 6,12C6,11 6.25,10.03 6.7,9.2L5.24,7.74C4.46,8.97 4,10.43 4,12A8,8 0 0,0 12,20V23L16,19L12,15M12,4V1L8,5L12,9V6A6,6 0 0,1 18,12C18,13 17.75,13.97 17.3,14.8L18.76,16.26C19.54,15.03 20,13.57 20,12A8,8 0 0,0 12,4Z" />
              </svg>
              <span class="sync-text">{{ syncStatus.pendingCount }} 项待同步</span>
              <button 
                class="retry-sync-btn" 
                @click="retrySyncPendingData" 
                :disabled="syncStatus.isRetrying"
                title="重试同步"
              >
                <svg viewBox="0 0 24 24" width="10" height="10">
                  <path fill="currentColor" d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A1,1 0 0,0 2,12A10,10 0 0,1 12,2C14.73,2 17.17,3.14 18.95,5.05L21,3V9H15L17.65,6.35M7.35,17.65C8.8,19.1 10.79,20 13,20A8,8 0 0,0 21,12A1,1 0 0,0 23,12A10,10 0 0,1 13,22C10.27,22 7.83,20.86 6.05,18.95L4,21V15H10L7.35,17.65Z" />
                </svg>
              </button>
            </div>
            <div v-else class="sync-complete">
              <svg viewBox="0 0 24 24" width="12" height="12" class="sync-icon complete">
                <path fill="currentColor" d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z" />
              </svg>
              <span class="sync-text">已同步</span>
            </div>
          </div>
        </div>
      </div>
      <div class="user-actions">
        <button v-if="!isLoggedIn" class="action-btn login-btn" @click="showLogin" title="登录">
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path
              fill="currentColor"
              d="M10,17V14H3V10H10V7L15,12L10,17M10,2H19A2,2 0 0,1 21,4V20A2,2 0 0,1 19,22H10A2,2 0 0,1 8,20V18H10V20H19V4H10V6H8V4A2,2 0 0,1 10,2Z"
            />
          </svg>
        </button>

<!-- 同步按钮已删除 -->
         <button class="action-btn settings-btn" @click="$emit('showSettings')" title="设置">
           <svg viewBox="0 0 24 24" width="16" height="16">
             <path fill="currentColor" d="M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.22,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.22,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.68 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z"/>
           </svg>
         </button>
        <button v-if="isLoggedIn" class="action-btn logout-btn" @click="handleLogout" title="登出">
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path
              fill="currentColor"
              d="M16,17V14H9V10H16V7L21,12L16,17M14,2A2,2 0 0,1 16,4V6H14V4H5V20H14V18H16V20A2,2 0 0,1 14,22H5A2,2 0 0,1 3,20V4A2,2 0 0,1 5,2H14Z"
            />
          </svg>
        </button>
      </div>
    </div>

    <!-- 可滚动的内容区域 -->
    <div class="scrollable-content">
      <!-- 默认笔记区域 -->
    <div class="default-notes-section">
      <div class="section-header">
        <h3 class="section-title">默认笔记</h3>
      </div>
      <div class="default-notes-list">
        <div
          v-for="folder in visibleFolders.filter((f) => f.isDefault)"
          :key="folder.id"
          class="folder-item default-note-item"
          :class="{ active: currentFolder === folder.name }"
          @click="handleFolderClick(folder)"
        >
          <div class="folder-info">
            <svg class="folder-icon" viewBox="0 0 24 24" width="16" height="16">
              <path
                fill="currentColor"
                d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"
              />
            </svg>
            <span class="folder-name" :title="folder.name">{{ truncateFolderName(folder.name) }}</span>
            <!-- 展开状态指示器 -->
            <span v-if="hasChildren(folder.id)" class="expand-indicator">
              <svg viewBox="0 0 24 24" width="12" height="12">
                <path
                  fill="currentColor"
                  :d="isFolderExpanded(folder.id) ? 'M7,10L12,15L17,10H7Z' : 'M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z'"
                />
              </svg>
            </span>
          </div>
          <div class="folder-right">
            <span class="folder-count">{{ folder.count }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 我的文件夹区域 -->
    <div class="folders-section">
      <div class="section-header">
        <div 
          class="section-title-wrapper root-drop-zone"
          :class="{ 'drag-over': dragOverFolderId === 'root' }"
          @dragover="handleRootDragOver($event)"
          @dragleave="handleRootDragLeave($event)"
          @drop="handleRootDrop($event)"
          title="拖拽文件夹到此处移动到根目录"
        >
          <h3 class="section-title">我的文件夹</h3>
        </div>
        <button class="add-folder-btn" @click="showCreateFolder" title="新建文件夹">
          <svg viewBox="0 0 24 24" width="14" height="14">
            <path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
          </svg>
        </button>
      </div>
      <div class="folder-list">
        <div
          v-for="folder in visibleFolders.filter((f) => !f.isDefault)"
          :key="folder.id"
          class="folder-item"
          :class="{ 
            active: currentFolder === folder.name,
            'drag-over': dragOverFolderId === folder.id,
            'being-dragged': draggedFolderId === folder.id
          }"
          :style="{ 
            position: 'relative',
            marginLeft: getFolderDepth(folder) * 16 + 'px',
            width: `calc(100% - ${getFolderDepth(folder) * 16}px)`
          }"
          :draggable="true"
          @click="handleFolderClick(folder)"
          @contextmenu="showFolderContextMenu(folder, $event)"
          @dragstart="handleDragStart(folder, $event)"
          @dragend="handleDragEnd($event)"
          @dragover="handleDragOver(folder, $event)"
          @dragleave="handleDragLeave($event)"
          @drop="handleDrop(folder, $event)"
        >
          <!-- 层级连接线 -->
          <div 
            v-if="getFolderDepth(folder) > 0" 
            class="hierarchy-lines"
            :style="{ left: '-8px' }"
          >
            <div class="hierarchy-line"></div>
          </div>
          
          <!-- 文件夹显示 -->
          <div class="folder-info">
            <!-- 统一使用文件夹图标，支持颜色自定义 -->
            <svg class="folder-icon" viewBox="0 0 24 24" width="16" height="16" :style="{ color: folder.iconColor || '#6c757d' }">
              <path
                fill="currentColor"
                d="M10 4H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2h-8l-2-2z"
              />
            </svg>
            <span class="folder-name" :title="folder.name">{{ truncateFolderName(folder.name) }}</span>
            <!-- 展开状态指示器 -->
            <span v-if="hasChildren(folder.id)" class="expand-indicator">
              <svg viewBox="0 0 24 24" width="12" height="12">
                <path
                  fill="currentColor"
                  :d="isFolderExpanded(folder.id) ? 'M7,10L12,15L17,10H7Z' : 'M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z'"
                />
              </svg>
            </span>
          </div>
          <div class="folder-right">
            <span class="folder-count">{{ folder.count }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 共享文件夹区域 -->
    <div class="shared-folders-section" :style="{ height: sharedFoldersHeight + 'px' }">
      <div class="section-header">
        <h3 class="section-title">共享文件夹</h3>
        <button class="add-folder-btn" @click="showAddSharedFolderModal" title="添加共享文件夹">
          <svg viewBox="0 0 24 24" width="14" height="14">
            <path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
          </svg>
        </button>
      </div>
      <div class="shared-folder-list">
         <div
           v-for="folder in getSharedFoldersFlat()"
           :key="'shared-' + folder.id"
           class="folder-item shared-folder-item"
           :class="{ active: currentFolder === folder.name }"
           @click="selectFolder(folder)"
           @contextmenu="showFolderContextMenu(folder, $event)"
         >
           <div class="folder-info">             
             <!-- 统一使用文件夹图标，支持颜色自定义 -->
             <svg class="folder-icon shared-folder-icon" viewBox="0 0 24 24" width="16" height="16" :style="{ color: folder.iconColor || '#007bff' }">
               <path
                 fill="currentColor"
                 d="M10 4H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2h-8l-2-2z"
               />
             </svg>
             <span class="folder-name" :title="folder.name">{{ truncateFolderName(folder.name) }}</span>
           </div>
           <div class="folder-right">
             <span class="folder-count">{{ folder.count }}</span>
           </div>
         </div>
       </div>
    </div>
    </div> <!-- 关闭可滚动内容区域 -->
    
    <!-- 拖动分隔条 -->
    <div 
      class="resize-handle" 
      :class="{ dragging: isDragging }"
      @mousedown="startDragging"
      title="拖动调整共享文件夹区域高度"
    >
      <div class="resize-handle-line"></div>
    </div>

    <!-- 文件夹弹窗 -->
    <FolderModal
      :show="showModal"
      :title="modalTitle"
      :initial-value="modalInitialValue"
      @confirm="handleModalConfirm"
      @close="handleModalClose"
    />

    <!-- 登录弹窗 -->
     <LoginModal 
       :show="showLoginModal" 
       :error="loginError"
       :success="loginSuccess"
       @login="handleLogin" 
       @register="handleRegister"
       @close="closeLoginModal" 
     />

     <!-- 修改密码弹窗 -->
     <ChangePasswordModal 
       :show="showChangePasswordModal" 
       @success="handlePasswordChangeSuccess"
       @close="closeChangePasswordModal" 
     />

     <!-- 共享链接弹窗 -->
     <div v-if="showShareLinkModal" class="modal-overlay" @click="closeShareLinkModal">
       <div class="modal-content share-link-modal" @click.stop>
         <div class="modal-header">
           <h3>共享链接</h3>
           <button class="close-btn" @click="closeShareLinkModal">
             <svg viewBox="0 0 24 24" width="20" height="20">
               <path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" />
             </svg>
           </button>
         </div>
         
         <div class="modal-body">
           <div class="share-link-section">
             <label class="form-label">共享链接</label>
             <div class="link-input-group">
               <input 
                 v-model="shareLink" 
                 type="text" 
                 class="link-input" 
                 readonly 
                 placeholder="生成中..."
               />
               <button 
                 class="copy-btn" 
                 @click="copyShareLink"
                 :disabled="!shareLink"
               >
                 <svg viewBox="0 0 24 24" width="16" height="16">
                   <path fill="currentColor" d="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z" />
                 </svg>
                 复制
               </button>
             </div>
           </div>
           
           <div v-if="sharePassword" class="share-password-section">
             <label class="form-label">访问密码</label>
             <div class="password-display">
               <code>{{ sharePassword }}</code>
             </div>
           </div>
           
           <div class="share-info">
             <p class="info-text">
               <svg viewBox="0 0 24 24" width="16" height="16">
                 <path fill="currentColor" d="M13,9H11V7H13M13,17H11V11H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
               </svg>
               任何拥有此链接的人都可以访问该文件夹及其内容
             </p>
           </div>
         </div>
         
         <div class="modal-footer">
           <button class="btn btn-secondary" @click="closeShareLinkModal">关闭</button>
         </div>
       </div>
     </div>

    <!-- 添加共享文件夹弹窗 -->
    <div v-if="showAddSharedModal" class="modal-overlay" @click="closeAddSharedModal">
      <div class="modal-content add-shared-modal" @click.stop>
        <div class="modal-header">
          <h3>添加共享文件夹</h3>
          <button class="close-btn" @click="closeAddSharedModal">
            <svg viewBox="0 0 24 24" width="20" height="20">
              <path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" />
            </svg>
          </button>
        </div>
        
        <div class="modal-body">
          <div class="shared-link-input-section">
            <label class="form-label">共享链接</label>
            <div class="input-group">
              <input 
                v-model="sharedLinkInput" 
                type="text" 
                class="shared-link-input" 
                placeholder="请输入共享文件夹链接"
                @keyup.enter="handleAddSharedFolder"
              />
            </div>
            <div v-if="sharedFolderError" class="error-message">
              <svg viewBox="0 0 24 24" width="16" height="16">
                <path fill="currentColor" d="M13,13H11V7H13M13,17H11V15H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
              </svg>
              {{ sharedFolderError }}
            </div>
          </div>
          
          <div class="shared-info">
            <p class="info-text">
              <svg viewBox="0 0 24 24" width="16" height="16">
                <path fill="currentColor" d="M13,9H11V7H13M13,17H11V11H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
              </svg>
              输入共享链接后，系统将自动获取并添加共享文件夹到您的列表中
            </p>
          </div>
        </div>
        
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeAddSharedModal">取消</button>
          <button 
            class="btn btn-primary" 
            @click="handleAddSharedFolder"
            :disabled="isLoadingSharedFolder || !sharedLinkInput.trim()"
          >
            <span v-if="isLoadingSharedFolder">获取中...</span>
            <span v-else>添加</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 右键菜单 -->
    <div
      v-if="showContextMenu"
      class="context-menu"
      :style="{ left: contextMenuX + 'px', top: contextMenuY + 'px' }"
      @click.stop
    >
      <!-- 我的文件夹共享设置 -->
      <div 
        v-if="contextMenuFolder && !contextMenuFolder.isDefault && !contextMenuFolder.isShared" 
        class="context-menu-item" 
        @click="contextMenuSetShared"
      >
        <svg viewBox="0 0 24 24" width="16" height="16">
          <path
            fill="currentColor"
            d="M18,16.08C17.24,16.08 16.56,16.38 16.04,16.85L8.91,12.7C8.96,12.47 9,12.24 9,12C9,11.76 8.96,11.53 8.91,11.3L15.96,7.19C16.5,7.69 17.21,8 18,8A3,3 0 0,0 21,5A3,3 0 0,0 18,2A3,3 0 0,0 15,5C15,5.24 15.04,5.47 15.09,5.7L8.04,9.81C7.5,9.31 6.79,9 6,9A3,3 0 0,0 3,12A3,3 0 0,0 6,15C6.79,15 7.5,14.69 8.04,14.19L15.16,18.34C15.11,18.55 15.08,18.77 15.08,19C15.08,20.61 16.39,21.91 18,21.91C19.61,21.91 20.92,20.61 20.92,19A2.92,2.92 0 0,0 18,16.08Z"
          />
        </svg>
        设置为共享
      </div>
      
      <!-- 共享文件夹专用菜单项 -->
      <div 
        v-if="contextMenuFolder?.isShared" 
        class="context-menu-item" 
        @click="contextMenuGetShareLink"
      >
        <svg viewBox="0 0 24 24" width="16" height="16">
          <path
            fill="currentColor"
            d="M3.9,12C3.9,10.29 5.29,8.9 7,8.9H11V7H7A5,5 0 0,0 2,12A5,5 0 0,0 7,17H11V15.1H7C5.29,15.1 3.9,13.71 3.9,12M8,13H16V11H8V13M17,7H13V8.9H17C18.71,8.9 20.1,10.29 20.1,12C20.1,13.71 18.71,15.1 17,15.1H13V17H17A5,5 0 0,0 22,12A5,5 0 0,0 17,7Z"
          />
        </svg>
        获取共享链接
      </div>
      
      <!-- 颜色选择菜单 -->
      <div 
        v-if="contextMenuFolder && !contextMenuFolder.isDefault" 
        class="context-menu-item submenu-item"
      >
        <svg viewBox="0 0 24 24" width="16" height="16">
          <path
            fill="currentColor"
            d="M17.5,12A1.5,1.5 0 0,1 16,10.5A1.5,1.5 0 0,1 17.5,9A1.5,1.5 0 0,1 19,10.5A1.5,1.5 0 0,1 17.5,12M14.5,8A1.5,1.5 0 0,1 13,6.5A1.5,1.5 0 0,1 14.5,5A1.5,1.5 0 0,1 16,6.5A1.5,1.5 0 0,1 14.5,8M9.5,8A1.5,1.5 0 0,1 8,6.5A1.5,1.5 0 0,1 9.5,5A1.5,1.5 0 0,1 11,6.5A1.5,1.5 0 0,1 9.5,8M6.5,12A1.5,1.5 0 0,1 5,10.5A1.5,1.5 0 0,1 6.5,9A1.5,1.5 0 0,1 8,10.5A1.5,1.5 0 0,1 6.5,12M12,3A9,9 0 0,0 3,12A9,9 0 0,0 12,21A1.5,1.5 0 0,0 13.5,19.5C13.5,19.11 13.35,18.76 13.11,18.5C12.88,18.23 12.73,17.88 12.73,17.5A1.5,1.5 0 0,1 14.23,16H16A5,5 0 0,0 21,11C21,6.58 16.97,3 12,3Z"
          />
        </svg>
        更改颜色
        <svg class="submenu-arrow" viewBox="0 0 24 24" width="12" height="12">
          <path fill="currentColor" d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z" />
        </svg>
        <div class="color-submenu">
          <div 
            v-for="color in folderColors" 
            :key="color.value"
            class="color-option"
            :style="{ backgroundColor: color.value }"
            :title="color.name"
            @click="changeFolderColor(color.value)"
          >
          </div>
        </div>
      </div>
      
      <div 
        v-if="contextMenuFolder?.isShared" 
        class="context-menu-item" 
        @click="contextMenuCancelShared"
      >
        <svg viewBox="0 0 24 24" width="16" height="16">
          <path
            fill="currentColor"
            d="M12,2C17.53,2 22,6.47 22,12C22,17.53 17.53,22 12,22C6.47,22 2,17.53 2,12C2,6.47 6.47,2 12,2M15.59,7L12,10.59L8.41,7L7,8.41L10.59,12L7,15.59L8.41,17L12,13.41L15.59,17L17,15.59L13.41,12L17,8.41L15.59,7Z"
          />
        </svg>
        取消共享
      </div>
      
      <!-- 分隔线 -->
      <div v-if="contextMenuFolder && (contextMenuFolder.isShared || (!contextMenuFolder.isDefault && !contextMenuFolder.isShared))" class="context-menu-divider"></div>
      
      <!-- 排序菜单项 -->
      <div 
        v-if="contextMenuFolder && !contextMenuFolder.isDefault && canMoveUp(contextMenuFolder)"
        class="context-menu-item" 
        @click="contextMenuMoveUp"
      >
        <svg viewBox="0 0 24 24" width="16" height="16">
          <path
            fill="currentColor"
            d="M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z"
          />
        </svg>
        上移
      </div>
      
      <div 
        v-if="contextMenuFolder && !contextMenuFolder.isDefault && canMoveDown(contextMenuFolder)"
        class="context-menu-item" 
        @click="contextMenuMoveDown"
      >
        <svg viewBox="0 0 24 24" width="16" height="16">
          <path
            fill="currentColor"
            d="M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z"
          />
        </svg>
        下移
      </div>
      
      <!-- 排序分隔线 -->
      <div v-if="contextMenuFolder && !contextMenuFolder.isDefault && (canMoveUp(contextMenuFolder) || canMoveDown(contextMenuFolder))" class="context-menu-divider"></div>
      
      <!-- 通用菜单项 -->
      <div class="context-menu-item" @click="contextMenuRename">
        <svg viewBox="0 0 24 24" width="16" height="16">
          <path
            fill="currentColor"
            d="M20.71,7.04C21.1,6.65 21.1,6 20.71,5.63L18.37,3.29C18,2.9 17.35,2.9 16.96,3.29L15.12,5.12L18.87,8.87M3,17.25V21H6.75L17.81,9.93L14.06,6.18L3,17.25Z"
          />
        </svg>
        重命名
      </div>
      <div class="context-menu-item delete" @click="contextMenuDelete">
        <svg viewBox="0 0 24 24" width="16" height="16">
          <path
            fill="currentColor"
            d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"
          />
        </svg>
        删除
      </div>
    </div>
  </div>
</template>

<style scoped>
.folder-list-container {
  width: 250px;
  height: 100vh;
  background: #e9ecef;
  border-right: 1px solid #dee2e6;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.user-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #dee2e6;
  background: #e9ecef;
  height: 64px;
  min-height: 64px;
  box-sizing: border-box;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #007bff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 500;
  font-size: 14px;
  flex-shrink: 0;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.sync-status {
  display: flex;
  align-items: center;
  margin-top: 2px;
}

.pending-sync-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: #fd7e14;
}

.sync-complete {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: #28a745;
}

.sync-icon {
  flex-shrink: 0;
}

.sync-icon.complete {
  color: #28a745;
}

.sync-text {
  font-size: 11px;
  white-space: nowrap;
}

.retry-sync-btn {
  padding: 2px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 2px;
  color: #fd7e14;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.retry-sync-btn:hover:not(:disabled) {
  background: rgba(253, 126, 20, 0.1);
  color: #e8690b;
}

.retry-sync-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.sync-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: 500;
}

.sync-indicator.syncing {
  color: #17a2b8;
  background: rgba(23, 162, 184, 0.1);
}

.sync-indicator.offline {
  color: #6c757d;
  background: rgba(108, 117, 125, 0.1);
}

.sync-indicator.error {
  color: #dc3545;
  background: rgba(220, 53, 69, 0.1);
}

.sync-indicator.pending {
  color: #fd7e14;
  background: rgba(253, 126, 20, 0.1);
}

.sync-indicator.synced {
  color: #28a745;
  background: rgba(40, 167, 69, 0.1);
}

.sync-indicator .spinning {
  animation: spin 1s linear infinite;
}

.user-actions {
  display: flex;
  gap: 4px;
}

.action-btn {
  padding: 6px;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6c757d;
  transition: all 0.2s;
}

.action-btn:hover {
  background: #f8f9fa;
  border-color: #007bff;
  color: #007bff;
}

.login-btn:hover {
  border-color: #28a745;
  color: #28a745;
}

.sync-btn:hover {
  border-color: #17a2b8;
  color: #17a2b8;
}

.image-btn:hover {
  border-color: #6f42c1;
  color: #6f42c1;
}

.settings-btn:hover {
  border-color: #fd7e14;
  color: #fd7e14;
}

.logout-btn:hover {
  border-color: #dc3545;
  color: #dc3545;
}

.indexeddb-sync-btn:hover {
  border-color: #6f42c1;
  color: #6f42c1;
}

.user-info.clickable {
  cursor: pointer;
}

.user-info.clickable:hover {
  background: rgba(0, 123, 255, 0.1);
  border-radius: 4px;
}

/* 可滚动内容区域 */
.scrollable-content {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.folders-section {
  padding: 16px;
  padding-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.section-title {
  font-size: 13px;
  font-weight: 500;
  color: #8e8e93;
  margin: 0;
  text-transform: none;
  letter-spacing: 0;
}

.add-folder-btn {
  padding: 4px;
  border: none;
  border-radius: 4px;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6c757d;
  transition: all 0.2s;
}

.add-folder-btn:hover {
  background: #e9ecef;
  color: #007bff;
}

.folder-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.folder-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s ease;
  position: relative;
  margin-bottom: 2px;
}

.folder-item:hover {
  background: rgba(0, 0, 0, 0.04);
}

.folder-item:hover .folder-menu {
  opacity: 1;
}

.folder-item.active {
  background: rgba(0, 123, 255, 0.08);
  color: #007bff;
  border-radius: 6px;
  font-weight: 500;
  position: relative;
}

.folder-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 60%;
  background: #007bff;
  border-radius: 0 2px 2px 0;
}

.action-btn {
  padding: 4px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.action-btn.confirm {
  background: #28a745;
  color: white;
}

.action-btn.confirm:hover {
  background: #218838;
}

.action-btn.cancel {
  background: #6c757d;
  color: white;
}

.action-btn.cancel:hover {
  background: #5a6268;
}

.folder-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.expand-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6c757d;
  transition: all 0.2s ease;
  width: 16px;
  height: 16px;
  flex-shrink: 0;
  margin-left: auto;
}

.folder-item:hover .expand-indicator {
  color: #495057;
}

.folder-icon {
  flex-shrink: 0;
  transition: color 0.15s ease;
  width: 16px;
  height: 16px;
}

.private-folder-icon {
  color: #8e8e93;
}

.shared-folder-icon {
  color: #8e8e93;
}

.folder-item:hover .private-folder-icon,
.folder-item:hover .shared-folder-icon {
  color: #007aff;
}

.folder-item:hover .shared-folder-icon {
  color: #1e7e34;
}

.folder-item.active .folder-icon {
  color: #007bff;
}

.folder-name {
  font-size: 14px;
  font-weight: 400;
  color: #1d1d1f;
}

.folder-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  min-width: 40px;
}

.folder-count {
  font-size: 13px;
  color: #8e8e93;
  background: transparent;
  padding: 0;
  border-radius: 0;
  min-width: auto;
  text-align: right;
  font-weight: 400;
}

.folder-item.active .folder-count {
}

.folder-menu {
  display: flex;
  gap: 2px;
  opacity: 0;
  transition: opacity 0.2s;
}

.menu-btn {
  padding: 4px;
  border: none;
  border-radius: 3px;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6c757d;
  transition: all 0.2s;
}

.menu-btn:hover {
  background: rgba(0, 0, 0, 0.1);
  color: #007bff;
}

.menu-btn.delete:hover {
  color: #dc3545;
}

.folder-item.active .menu-btn {
  color: rgba(255, 255, 255, 0.7);
}

.folder-item.active .menu-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  color: white;
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.action-btn:disabled:hover {
  background: transparent;
}

.sync-btn {
  position: relative;
}

.sync-icon-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.warning-icon {
  position: absolute;
  top: -2px;
  right: -2px;
  background: white;
  border-radius: 50%;
}

.sync-btn.sync-error {
  background: rgba(220, 53, 69, 0.1);
  color: #dc3545;
}

.sync-btn.sync-error .warning-icon {
  color: #dc3545;
}

.sync-btn.sync-offline {
  background: rgba(253, 126, 20, 0.1);
  color: #fd7e14;
}

.sync-btn.sync-offline .warning-icon {
  color: #fd7e14;
}

.sync-btn.sync-pending {
  background: rgba(255, 193, 7, 0.1);
  color: #ffc107;
}

.sync-btn.sync-normal {
  background: rgba(40, 167, 69, 0.1);
  color: #28a745;
}

.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.folder-item.drag-over {
  background: #e3f2fd;
  border: 2px dashed #2196f3;
}

.folder-item.being-dragged {
  opacity: 0.5;
  transform: scale(0.95);
}

.folder-item[draggable='true'] {
  cursor: move;
}

.folder-item[draggable='false'] {
  cursor: pointer;
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 120px;
  padding: 4px 0;
}

.context-menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
  color: #495057;
  transition: background-color 0.2s;
}

.context-menu-item:hover {
  background: #f8f9fa;
}

.context-menu-item.delete {
  color: #dc3545;
}

.context-menu-item.delete:hover {
  background: #f8d7da;
}

.context-menu-divider {
  height: 1px;
  background: #e9ecef;
  margin: 4px 0;
}

/* 共享链接弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.share-link-modal {
  width: 480px;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #e9ecef;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

.close-btn {
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
  border-radius: 4px;
  color: #6c757d;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #f8f9fa;
  color: #495057;
}

.modal-body {
  padding: 20px 24px;
}

.share-link-section {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #495057;
  font-size: 14px;
}

.link-input-group {
  display: flex;
  gap: 8px;
}

.link-input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
  background: #f8f9fa;
  color: #495057;
}

.copy-btn {
  padding: 10px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.2s ease;
}

.copy-btn:hover:not(:disabled) {
  background: #0056b3;
}

.copy-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.share-password-section {
  margin-bottom: 20px;
}

.password-display {
  padding: 10px 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
}

.password-display code {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  color: #495057;
  background: none;
  padding: 0;
}

.share-info {
  padding: 12px;
  background: #e7f3ff;
  border: 1px solid #b8daff;
  border-radius: 4px;
}

.info-text {
  margin: 0;
  font-size: 13px;
  color: #004085;
  display: flex;
  align-items: flex-start;
  gap: 8px;
  line-height: 1.4;
}

.info-text svg {
  flex-shrink: 0;
  margin-top: 1px;
}

.modal-footer {
  padding: 16px 24px 20px;
  border-top: 1px solid #e9ecef;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

/* 默认笔记区域样式 */
.default-notes-section {
  padding: 16px;
  padding-bottom: 0;
}

.default-notes-section .section-title {
  color: #495057;
  font-weight: 600;
}

/* 我的文件夹区域样式 - 与默认笔记保持一致 */
.folders-section .section-title {
  color: #495057;
  font-weight: 600;
}

.default-note-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s ease;
  position: relative;
  margin-bottom: 2px;
  background: transparent;
  border: none;
}

.default-note-item:hover {
  background: rgba(0, 0, 0, 0.05);
}

.default-note-item.active {
  background: rgba(0, 123, 255, 0.08);
  color: #007bff;
  border-radius: 6px;
  font-weight: 500;
  position: relative;
}

.default-note-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 60%;
  background: #007bff;
  border-radius: 0 2px 2px 0;
}

.default-note-item .folder-icon {
  color: #6c757d;
}

.default-note-item.active .folder-icon {
  color: #007bff;
}

/* 共享文件夹区域样式 */
.shared-folders-section {
  padding: 16px;
  overflow-y: auto;
  min-height: 100px;
  max-height: 400px;
}

.shared-folder-list {
  height: calc(100% - 40px); /* 减去header高度 */
  overflow-y: auto;
}

/* 拖动分隔条样式 */
.resize-handle {
  height: 8px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  border-bottom: 1px solid #e9ecef;
  cursor: ns-resize;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
  position: relative;
}

.resize-handle:hover {
  background: #e9ecef;
}

.resize-handle.dragging {
  background: #007bff;
}

.resize-handle-line {
  width: 40px;
  height: 2px;
  background: #6c757d;
  border-radius: 1px;
  transition: background-color 0.2s;
}

.resize-handle:hover .resize-handle-line {
  background: #495057;
}

.resize-handle.dragging .resize-handle-line {
  background: white;
}

.shared-folders-section .section-title {
  color: #495057;
  font-weight: 600;
}

.shared-folder-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s ease;
  position: relative;
  margin-bottom: 2px;
  background: transparent;
  border: none;
}

.shared-folder-item:hover {
  background: rgba(0, 0, 0, 0.05);
}

.shared-folder-item.active {
  background: rgba(0, 123, 255, 0.08);
  color: #007bff;
  border-radius: 6px;
  font-weight: 500;
  position: relative;
}

.shared-folder-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 60%;
  background: #007bff;
  border-radius: 0 2px 2px 0;
}

.shared-folder-item .folder-icon {
  color: inherit;
}

.shared-folder-item.active .folder-icon {
  color: inherit;
}

/* 我的文件夹区域调整 - 已在上面定义 */

/* 移除共享文件夹在我的文件夹中的特殊样式 */

/* 文件夹拖拽样式 */
.folder-item[draggable="true"] {
  cursor: move;
}

.folder-item.being-dragged {
  opacity: 0.5;
  transform: scale(0.95);
  transition: all 0.2s ease;
}

.folder-item.drag-over {
  background: #e3f2fd;
  border: 2px dashed #2196f3;
  border-radius: 4px;
  transform: scale(1.02);
  transition: all 0.2s ease;
}

.folder-item.drag-over::before {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  background: rgba(33, 150, 243, 0.1);
  border-radius: 4px;
  pointer-events: none;
 }
 
 /* 添加共享文件夹弹窗样式 */
 .add-shared-modal {
   width: 480px;
 }
 
 .shared-link-input-section {
   margin-bottom: 20px;
 }
 
 .shared-link-input {
   width: 100%;
   padding: 10px 12px;
   border: 1px solid #ced4da;
   border-radius: 4px;
   font-size: 14px;
   transition: border-color 0.2s ease;
 }
 
 .shared-link-input:focus {
   outline: none;
   border-color: #007bff;
   box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
 }
 
 .error-message {
   display: flex;
   align-items: center;
   gap: 6px;
   margin-top: 8px;
   padding: 8px 12px;
   background: #f8d7da;
   border: 1px solid #f5c6cb;
   border-radius: 4px;
   color: #721c24;
   font-size: 14px;
 }
 
 .error-message svg {
   flex-shrink: 0;
   color: #dc3545;
 }
 
 .shared-info {
   padding: 12px;
   background: #e7f3ff;
   border: 1px solid #b3d9ff;
   border-radius: 4px;
 }
 
 .btn-primary {
   background: #007bff;
   color: white;
   border: 1px solid #007bff;
 }
 
 .btn-primary:hover:not(:disabled) {
   background: #0056b3;
   border-color: #0056b3;
 }
 
 .btn-primary:disabled {
    background: #6c757d;
    border-color: #6c757d;
    cursor: not-allowed;
    opacity: 0.6;
  }
  
  /* 文件夹层级连接线样式 */
  .hierarchy-lines {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 1px;
    pointer-events: none;
  }
  
  .hierarchy-line {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 1px;
    background: #dee2e6;
    opacity: 0.6;
  }
  
  .hierarchy-line::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    width: 12px;
    height: 1px;
    background: #dee2e6;
    opacity: 0.6;
  }
  
  /* 文件夹项悬停时高亮层级线 */
  .folder-item:hover .hierarchy-line {
    background: #007bff;
    opacity: 0.8;
  }
  
  .folder-item:hover .hierarchy-line::before {
    background: #007bff;
    opacity: 0.8;
  }
  
  /* 激活状态的层级线 */
  .folder-item.active .hierarchy-line {
    background: #007bff;
    opacity: 1;
  }
  
  .folder-item.active .hierarchy-line::before {
     background: #007bff;
     opacity: 1;
   }
   
   /* 根目录拖拽样式应用到包装器 */
    .section-title-wrapper.root-drop-zone {
      cursor: pointer;
      transition: all 0.2s ease;
      border-radius: 4px;
      margin: 0;
    }
    
    .section-title-wrapper.root-drop-zone:hover {
      background: #e7f3ff;
    }
    
    .section-title-wrapper.root-drop-zone:hover .section-title {
      color: #007bff;
    }
    
    .section-title-wrapper.root-drop-zone.drag-over {
      background: #e7f3ff;
      border: 2px dashed #007bff;
      transform: scale(1.02);
      box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
    }
    
    .section-title-wrapper.root-drop-zone.drag-over .section-title {
      color: #007bff;
    }
    
    /* 确保包装器内的标题保持默认样式 */
    .section-title-wrapper .section-title {
      margin: 0;
      padding: 0;
      background: transparent;
      border: none;
      transition: color 0.2s ease;
    }
    
    /* 颜色选择菜单样式 */
    .submenu-item {
      position: relative;
    }
    
    .submenu-arrow {
      margin-left: auto;
      opacity: 0.6;
    }
    
    .color-submenu {
      position: absolute;
      left: 100%;
      top: 0;
      background: white;
      border: 1px solid #dee2e6;
      border-radius: 4px;
      padding: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      display: none;
      grid-template-columns: repeat(4, 1fr);
      gap: 6px;
      min-width: 120px;
      z-index: 1001;
    }
    
    .submenu-item:hover .color-submenu {
      display: grid;
    }
    
    .color-option {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      cursor: pointer;
      border: 2px solid transparent;
      transition: all 0.2s ease;
    }
    
    .color-option:hover {
      border-color: #333;
      transform: scale(1.1);
    }
    
    /* 文件夹图标左对齐样式 */
    .folder-info {
      display: flex;
      align-items: center;
      gap: 8px;
      flex: 1;
      min-width: 0;
      justify-content: flex-start;
    }
    
    .folder-icon {
      flex-shrink: 0;
    }
    
    .default-note-item .folder-info,
    .folder-item .folder-info {
      justify-content: flex-start;
    }
   </style>
